package com.google.enterprise.gcs.search;

import java.io.InputStream;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.util.Linkify;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class ItemDetail extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.itemdetail);        
        TextView tvtitle   = (TextView)findViewById(R.id.dtitle);
        TextView tvdesc   = (TextView)findViewById(R.id.ddescription);
        TextView tvurl   = (TextView)findViewById(R.id.durl);
        TextView tvprice   = (TextView)findViewById(R.id.dprice);
        ImageView ivurl   = (ImageView)findViewById(R.id.photo);
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        ListItem item = intent.getParcelableExtra("item");
        //title = item.getTitle();
        String description = item.getItemDescription();
        String url = item.getOfferURL();
        String image_url = item.getImageURL();
        String price = item.getPrice();

        new DownloadImageTask(ivurl).execute(image_url);                 
     
        Log.i("GCSSearch", "ItemDetail: Selected " + title);
        tvtitle.setText(title);
        tvdesc.setText(description);        
        tvurl.setText(url);
        Linkify.addLinks(tvurl, Linkify.ALL);
        tvprice.setText(price);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        @Override
        protected Bitmap doInBackground(String[]  urls) {
            String urldisplay = urls[0];
            Bitmap con = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                con = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return con;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }    

}
